const path = require('path');
const conn = require('../../server/libs/DB/Conn');
const { Server } = require('socket.io');
const { originList } = require('../../Config');
let eventList;

/*
* sockio后台入口
* 与路灯版本做了一些调整
* 之前的版本是通过eventAction来执行并在其中先require某一业务下的js文件 再触发emit和on时间
* 当前版本则去除了eventAction直接sockIO文件下建立具体的业务处理
* */
async function createConection(socket) {
    for (let event of eventList) {
        socket.on(event.eventName, (params) => {
            console.log(`监听:${event.eventName}`);
            let actionPath = path.join(__dirname, `./actions/${event.eventName}`);//引入对应的执行函数
            require(actionPath)(params, socket);//执行
        })
    }
}

async function createSocket(httpServer) {
    //监听socket连接
    const io = new Server(httpServer, {
        allowEIO3: true,
        cors: {
            origin: originList,
            credentials: true
        }
    });
    try {
        eventList = await conn('SELECT event_name eventName FROM event WHERE delete_sign = 1');//查询数据库中的事件列表并将值赋予eventList
        io.on('connection', createConection);
    } catch (e) {
        console.log(e);
    }
}

module.exports = createSocket;